﻿// Copyright (C) Jari Hautio <jari.hautio@iki.fi> 2009. Licensed under GPLv2. See LICENSE.txt in solution folder.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace RyijyApp
{
    public partial class PaletteForm : Form
    {
        List<CustomPalette> paletteList = new List<CustomPalette>();
        internal List<CustomPalette> PaletteList { get { return paletteList; } set { paletteList = value; } }
        private string searchPrompt = "";
        internal CustomPalette SourcePalette { get { return comboBoxSource.SelectedItem as CustomPalette; } }
//        public event EventHandler SourcePaletteChanged;
//        internal CustomPalette TargetPalette { get { return comboBoxTarget.SelectedItem as CustomPalette; } }
        CustomPalette targetPalette = null;
        internal CustomPalette TargetPalette { get { return targetPalette; } set { targetPalette = value; } }
        //        public event EventHandler TargetPaletteChanged;
        ColorItemBinder sourceBinder = new ColorItemBinder(new CustomPalette());
        ColorItemBinder targetBinder = new ColorItemBinder(new CustomPalette());
        Font greyFont;
        public PaletteForm()
        {
            InitializeComponent();
        }


        private void PaletteForm_Load(object sender, EventArgs e)
        {
            searchPrompt = textBoxFind.Text;

            // Load all colors palettes to combobox
            foreach (CustomPalette p in paletteList)
            {
                // use copies in source list to keep them from being edited
                comboBoxSource.Items.Add(new CustomPalette(p));
            }
            if (comboBoxSource.Items.Count > 0)
            {
                comboBoxSource.SelectedIndex = 0;
                sourceBinder = new ColorItemBinder(paletteList[0]);
            }

            targetBinder = new ColorItemBinder(TargetPalette);
            sourceBinder.ExcludePalette = targetBinder.Palette;
            dataGridView1.DataSource = targetBinder;
            dataGridViewSource.DataSource = sourceBinder;

            greyFont = new Font(textBoxFind.Font, FontStyle.Italic);
            textBoxFind.Font = greyFont;

            textBoxName.Text = TargetPalette.PaletteName;
 
        }

        private void buttonAdd_Click(object sender, EventArgs e)
        {
            CustomPalette target = TargetPalette;
            CustomPalette source = SourcePalette;
            if (target == null || source == null)
                return;
            foreach (DataGridViewRow row in dataGridViewSource.SelectedRows)
            {
                target.Colors.Add(new CustomPalette.ColorItem(row.DataBoundItem as CustomPalette.ColorItem));
            }
            targetBinder.RefreshColors();
            sourceBinder.RefreshColors();

        }

        private void buttonRemove_Click(object sender, EventArgs e)
        {
            CustomPalette target = TargetPalette;
            CustomPalette source = SourcePalette;
            if (target == null || source == null)
                return;
            foreach (DataGridViewRow row in dataGridView1.SelectedRows)
            {
                CustomPalette.ColorItem item = row.DataBoundItem as CustomPalette.ColorItem;
                if (item == null) continue;
                // remove from target palette
                target.RemoveColor(item.Color);
            }
            sourceBinder.RefreshColors();
            targetBinder.RefreshColors();

        }

        private void comboBoxSource_SelectedIndexChanged(object sender, EventArgs e)
        {
            CustomPalette source = comboBoxSource.SelectedItem as CustomPalette;
            if (source == null)
                return;
            sourceBinder.Palette = source;
        }

        private void textBoxFind_TextChanged(object sender, EventArgs e)
        {
            string text = textBoxFind.Text.ToLowerInvariant();
            if (textBoxFind.ForeColor == Color.FromKnownColor(KnownColor.WindowText))
            {
                dataGridViewSource.ClearSelection();
                foreach (DataGridViewRow row in dataGridViewSource.Rows)
                {
                    CustomPalette.ColorItem item = row.DataBoundItem as CustomPalette.ColorItem;
                    if (item.Name.ToLowerInvariant().Contains(text) ||
                        item.Text.ToLowerInvariant().Contains(text))
                    {
                        row.Selected = true;
                        dataGridViewSource.FirstDisplayedScrollingRowIndex = row.Index;
                        break;
                    }
                }
            }
        }

        private void textBoxFind_Enter(object sender, EventArgs e)
        {
            if (textBoxFind.ForeColor == Color.FromKnownColor(KnownColor.GrayText))
            {
                textBoxFind.Text = "";
                textBoxFind.ForeColor = Color.FromKnownColor(KnownColor.WindowText);
                textBoxFind.Font = Font;
            }

        }

        private void textBoxFind_Leave(object sender, EventArgs e)
        {
            if (textBoxFind.Text.Length == 0)
            {
                textBoxFind.ForeColor = Color.FromKnownColor(KnownColor.GrayText);
                textBoxFind.Text = searchPrompt;
                textBoxFind.Font = greyFont;
            }
        }

        private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            try
            {
                DataGridView dgv = sender as DataGridView;

                CustomPalette.ColorItem ci = dgv.Rows[e.RowIndex].DataBoundItem as CustomPalette.ColorItem;
                if (ci != null)
                {
                    e.CellStyle.BackColor = ci.Color;
                    if (e.DesiredType == typeof(string))
                    {
                        e.CellStyle.ForeColor = ci.Color.GetBrightness() < 0.4 ? Color.White : Color.Black;
                    }
                }
            }
            catch (Exception)
            {
            }
        }

        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex < 0) return;
            CustomPalette.ColorItem c = dataGridView1.Rows[e.RowIndex].DataBoundItem as CustomPalette.ColorItem;
            if (e.ColumnIndex == 3  && c != null)
            {
                colorDialog1.Color = c.Color;
                if (colorDialog1.ShowDialog() == DialogResult.OK)
                {
                    c.Color = colorDialog1.Color;
                    int[] colors = new int[1];
                    colorDialog1.CustomColors = colors;
                    colors[0] = Color.FromArgb(0, c.Color.B, c.Color.G, c.Color.R).ToArgb();
                    colorDialog1.FullOpen = true;
                    colorDialog1.AnyColor = true;
                    colorDialog1.SolidColorOnly = true;
                    dataGridView1.InvalidateRow( e.RowIndex );
                }
            }
        }


        private void textBoxRename_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
        {
            /*
            if (e.KeyCode == Keys.Return)
            {
                CustomPalette p = textBoxRename.Tag as CustomPalette;
                if (p != null && textBoxRename.Text.Length>0)
                {
                    p.PaletteName = textBoxRename.Text;
                    UpdateTargetPalettes();
                }
                textBoxRename.Visible = false;
                comboBoxTarget.Visible = true;
                comboBoxTarget.Focus();
            }
            else if (e.KeyCode == Keys.Escape)
            {
                textBoxRename.Visible = false;
                comboBoxTarget.Visible = true;
                comboBoxTarget.Focus();
            }
*/
        }

        private void textBoxRename_KeyPress(object sender, KeyPressEventArgs e)
        {
            string nokey = "\\/:*?\"<>|";
            if (nokey.Contains(e.KeyChar.ToString()))
                e.Handled = true;
        }

        private void buttonRevert_Click(object sender, EventArgs e)
        {
            if (TargetPalette != null&&
                TargetPalette.FileName!= "")
            {
                TargetPalette.Load(TargetPalette.FileName);
            }
        }

        private void buttonOK_Click(object sender, EventArgs e)
        {
            if (TargetPalette != null)
                TargetPalette.PaletteName = textBoxName.Text;
        }

        private void buttonLoad_Click(object sender, EventArgs e)
        {
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    Bitmap bm = new Bitmap(openFileDialog1.FileName);
                    labelFilename.Text = openFileDialog1.FileName;
                    drawingCanvas1.Picture = bm;
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            string s = comboBox1.SelectedItem.ToString();
            int pos = s.IndexOf('%');
            if (pos >=0)
                s = s.Substring(0, pos);
            int z = 0;
            if (int.TryParse(s, out z))
            {
                drawingCanvas1.Zoom = z / 100.0f;
            }
            else
            {
                drawingCanvas1.FitToWindow = true;
            }


        }

        private void drawingCanvas1_MouseClick(object sender, MouseEventArgs e)
        {
            if (TargetPalette == null) return;

            Color c = drawingCanvas1.GetPixel(e.Location);

            if (TargetPalette.Contains(c)) return;
            int n = TargetPalette.Colors.Count+1;
            CustomPalette.ColorItem newItem = new CustomPalette.ColorItem(n.ToString(), "", c);
            TargetPalette.Colors.Add(newItem);

            targetBinder.RefreshColors();
            sourceBinder.RefreshColors();


        }

        private void drawingCanvas1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
        }

        private void tabControl1_Selected(object sender, TabControlEventArgs e)
        {
            buttonAdd.Enabled = e.TabPageIndex == 0;
        }

        private void dataGridViewSource_CellMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            CustomPalette target = TargetPalette;
            CustomPalette source = SourcePalette;
            if (target == null || source == null)
                return;
            DataGridViewRow row = dataGridViewSource.Rows[e.RowIndex];

            target.Colors.Add(new CustomPalette.ColorItem(row.DataBoundItem as CustomPalette.ColorItem));

            targetBinder.RefreshColors();
            sourceBinder.RefreshColors();
        }


    }
}
